package com.demo.tx.seata;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.tx.dao.mapper.UserMapper;
import com.demo.tx.feign.SeataXAControllerClient;
import com.demo.tx.model.entity.User;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * xa模式事务
 * @author cyj
 */
@Slf4j
@Service
public class SeataXAService {

    @Resource
    private SeataService seataService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private SeataXAControllerClient seataXaControllerClient;

    /**
     * 调用第三方服务，一个服务数据插入成功，一个服务报异常
     * @param userId 用户id
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    public void insertThirdServiceError(Long userId) {
        log.info("插入数据：{}", userId);
        seataService.insert(userId);
        log.info("调用Controller插入数据");
        seataXaControllerClient.insert(userId);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId, userId);
        List<User> users = userMapper.selectList(queryWrapper);
        log.info("user 集合：{}", JSON.toJSONString(users));

        log.info("调用Controller error");
        seataXaControllerClient.insertError(userId);
    }
}
